<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/17
 * Time: 11:59
 */

namespace addons\seller\controller;


use app\common\Code;
use app\common\model\Community;
use app\common\model\CommunitySellerRelation;
use app\common\model\GoodsCategory;
use app\common\model\GoodsCategoryRelation;
use app\common\model\Order;
use app\common\model\Sellers;
use app\common\model\Trade;
use app\common\model\TradeOrder;
use app\common\OrderStatus;
use app\common\Session;

class App extends Common
{

    /**
     * 获取商家信息
     */
    public function seller_info()
    {
        $user = Session::get_local_seller();
        if (!$user) {
            response_json(Code::NO_SELLER);
        }
        if (isset($user->status) && $user->status === 0)
            response_json(Code::EXAMINING, $user);
        else
            response_json(Code::NONE, $user);
    }

    /**
     * 商家审核
     * 必要参数 seller_name 店铺名称;
     * 必要参数 true_name 店铺所属人真实姓名
     * 必要参数 seller_address 商家地址
     * 必要参数 telephone 联系方式
     * 非必要参数 head_img 用户头像
     * @return \think\response\Jsonp
     */
    public function seller_examine()
    {
        $param = input();
        $user = Session::get_local_user();
        if (!$user)  #用户没有登录
        {
            response_json(Code::NO_SELLER);
        }
        $param['user_id'] = $user->id;
        $result = $this->validate(
            $param,
            [
                'seller_name' => 'require',                        #店铺名称
                'true_name' => 'require',                          #店铺所属人真实姓名
                'seller_address' => 'require',                     #商家地址
                'telephone' => 'require|number',                   #联系方式
            ]);
        if (true !== $result) {
            response_json(Code::PARAM_ERROR);
        }
        $examine = Sellers::get_seller_by_user_id($user->id);
        if ($examine)   #编辑商家审核信息
        {
            Sellers::edit_seller($user->id, $param);
        } else         #新增商家审核信息
        {
            Sellers::add_seller($param);
        }
        response_json(Code::NONE);
    }

    /**
     * 得到商家商品列表
     * 非必要参数
     * search_ 商品名称
     * status 商品状态
     */
    public function get_seller_goods()
    {
        $seller = Session::get_local_seller();
        if (empty($seller)) {
            response_json(Code::NO_SELLER);
        }
        $param = input();
        $cond['seller_id'] = $seller->id;
        $goods = new \app\common\model\Goods();
        $list_ = $goods->list_($param, $cond);
        response_json(Code::NONE, $list_);
    }

    /**
     * 获取商品类型
     * 可选参数
     * goods_id 商品id
     */
    public function get_goods_category()
    {
        $param = input();
        $goods_category_model = new GoodsCategory();
        #获取有序排序的全部分类
        $goods_category = $goods_category_model->get_all_category();
        if (isset($param['goods_id']) && !empty($param['goods_id'])) {
            #获取已选的分类的id
            $relation_ = new GoodsCategoryRelation();
            $categoy_ids = $relation_->get_goods_category_ids($param['goods_id']);
        }
        $arr = [];
        foreach ($goods_category as $item) {
            if (isset($categoy_ids) && in_array($item['id'], $categoy_ids)) {
                $a1['is_checked'] = 1;
            } else {
                $a1['is_checked'] = 0;
            }
            $a1['id'] = $item['id'];
            $a1['pid'] = $item['pid'];
            $a1['category_name'] = $item['category_name'];
            $arr[$a1['id']] = $a1;
        }
        $goods_category = $goods_category_model->get_all_sort_List($arr);
        response_json(Code::NONE, $goods_category);
    }

    /**
     * 获取商品详情
     * 必要参数 goods_id 商品名称
     * @return \think\response\Jsonp
     */
    public function get_goods_info()
    {
        $param = input();
        $goods = new \app\common\model\Goods();
        $goods_info = $goods->fetch_by_id($param['goods_id']);
        $goods_category_model = new GoodsCategory();
        #获取有序排序的全部分类
        $goods_category = $goods_category_model->get_all_category();
        #获取已选的分类的id
        $relation_ = new GoodsCategoryRelation();
        $categoy_ids = $relation_->get_goods_category_ids($param['goods_id']);
        $arr = [];
        foreach ($goods_category as $item) {
            if (in_array($item['id'], $categoy_ids)) {
                $a1['is_checked'] = 1;
            } else {
                $a1['is_checked'] = 0;
            }
            $a1['id'] = $item['id'];
            $a1['pid'] = $item['pid'];
            $a1['category_name'] = $item['category_name'];
            $arr[$a1['id']] = $a1;
        }
        $goods_category = $goods_category_model->get_all_sort_List($arr);
        $data = [
            'goods_category' => $goods_category,
            'goods_info' => $goods_info
        ];
        response_json(Code::NONE, $data);
    }

    /**
     * 新增或编辑商品
     * 说明：goods_id 传并且非空，编辑，不传或者空，新增
     * 必须参数
     * goods_name         #商品名称
     * place_of_origin    #产地
     * image              #商品图片
     * pre_price          #商品原价
     * price              #商品现价
     * stock              #库存
     * weight             #商品重量
     * 非必须的参数
     * seo:优化, goods_category[]:分类，bar_code:编码,content:内容；
     */
    public function edit_goods()
    {
        $seller = Session::get_local_seller();
        if (empty($seller)) {
            response_json(Code::NO_SELLER);
        }
        $param = input();
        $result = $this->validate(
            $param,
            [
                'goods_name' => 'require',         #商品名称
                'image' => 'require',              #商品图片
                'price' => 'require|number|gt:0',      #商品现价
                'stock' => 'require|number|egt:0',     #库存
                'weight' => 'require|number|gt:0',     #商品重量
                # 非必须的 seo:优化, goods_category[]:分类，bar_code:编码,content:内容；
            ]);
        if (true !== $result) {
            response_json(Code::PARAM_ERROR);
        }
        $goods = new \app\common\model\Goods();
        $goods_category_relation = new GoodsCategoryRelation();
        if (isset($param['goods_id']) && !empty($param['goods_id'])) {      #编辑商品
            $goods_data = $goods->edit_goods($param['goods_id'], $param);
            if (isset($param['goods_category']) && !empty($param['goods_category'][0]) && $param['goods_category'][0] != 0) {
                //商品类型管理
                $goods_category_relation->delGoodsCategoryRelation($goods_data->id); #删除旧的商品分类关系数据
                $goods_category_relation->addListGoodsCategoryRelation($goods_data->id, $param['goods_category']);
            }
        } else {                      #新增商品
            $param['seller_id'] = $seller->id;
            $goods_data = $goods->add_goods($param);
            if (isset($param['goods_category'])) {
                $goods_category_relation->addListGoodsCategoryRelation($goods_data->id, $param['goods_category']);
            }
        }
        response_json(Code::NONE, Code::msg(Code::NONE));
    }

    /**
     * 商家的订单状态
     */
    public function get_seller_order_status()
    {
        $order_status = [
            [
                "ordr_status_id" => 0,
                "title" => "全部"
            ],
            [
                "ordr_status_id" => OrderStatus::DAIFAHUO,
                "title" => "待接单"
            ],
            [
                "ordr_status_id" => OrderStatus::YIJIEDAI,
                "title" => "已接单"
            ],
            [
                "ordr_status_id" => OrderStatus::QUERENSHOUHUO,
                "title" => "已配送"
            ],
            [
                "ordr_status_id" => OrderStatus::BEGIN_AFTER_SALE,
                "title" => "售后"
            ],
        ];
        response_json(Code::NONE, $order_status);
    }

    /**
     * 得到商家订单
     * 非必要参数：
     * order_status_id 订单状态
     *
     * 返回 list 中 有【yunxu_fahuo】表示需要进行确认发货处理
     */
    public function get_seller_order()
    {
        $seller = Session::get_local_seller();
        if (empty($seller)) {
            response_json(Code::NO_SELLER);
        }
        #订单列表数据
        $param = input();
        #筛选商家订单
        $cond['seller_id'] = $seller->id;
        if (isset($param["order_status_id"]) && $param["order_status_id"] != 0) {
            $cond['order_status_id'] = $param["order_status_id"];
        }
        $list_ = \app\api\service\Order::list_($cond);
        $data = [
            'order_data' => $list_
        ];
        response_json(Code::NONE, $data);
    }

    /**
     * 查看订单详情
     * 必要参数：
     * order_id,订单号
     */
    public function order_info()
    {
        $param = input();
        $order_data = \app\common\model\Order::get_one_order_($param['order_id']);  #获取订单信息
        $details_ = \app\common\model\Order::order_details($param['order_id']);     #获取子订单信息
        $relation_ = TradeOrder::get_trade_by_order_id($param['order_id']);
        $trade = Trade::get_trade_by_code(isset($relation_->code) ? $relation_->code : 0);
        $data = [
            'order_data' => $order_data,
            'order_detail' => $details_,
            'trade' => $trade
        ];
        response_json(Code::NONE, $data);
    }

    /**
     *商家社区订单商品统计
     */
    public function order_goods_()
    {
        $seller = Session::get_local_seller();
        if (empty($seller)) {
            response_json(Code::NO_LOGIN);
        }
        $order_status = OrderStatus::DAIFAHUO;
        $data = \addons\admin\service\Order::community_order_goods($seller->id, $order_status);
        $res = [];
        foreach ($data as $c_k => $c_v) {
            SUPPLY_SELLER_:
            $k = $c_v['community_id'];
            if (isset($res[$k])) {
                $goods_id = $c_v["goods_id"];
                $res[$k]['community_id'] = $c_v['community_id'];
                $res[$k]['community_name'] = $c_v['community_name'];
                SUPPLY_GOODS:
                if (isset($res[$k]["data"][$goods_id])) {
                    $res[$k]["data"][$goods_id]["goods_id"] = $goods_id;
                    $res[$k]["data"][$goods_id]["goods_name"] = $c_v["goods_name"];
                    $res[$k]["data"][$goods_id]["price"] = $c_v["price"];
                    $res[$k]["data"][$goods_id]["count"] += $c_v["count"];
                } else {
                    $res[$k]["data"][$goods_id]["goods_id"] = 0;
                    $res[$k]["data"][$goods_id]["goods_name"] = 0;
                    $res[$k]["data"][$goods_id]["price"] = 0;
                    $res[$k]["data"][$goods_id]["count"] = 0;
                    goto SUPPLY_GOODS;
                }
            } else {
                $res[$k] = [];
                $res[$k]['data'] = [];
                goto SUPPLY_SELLER_;
            }
        }
        response_json(Code::NONE, $res);
    }

    /**
     * 社区列表
     * 参数 ad_code
     */
    public function community_list()
    {
        $param = input();
        $seller = Session::get_local_seller();
        if (!$seller)  #用户没有登录
        {
            response_json(Code::NO_SELLER);
        }
        $cond = [];
        if(isset($param["ad_code"]) && !empty($param["ad_code"])){
            $cond["county_id"]=$param["ad_code"];
        }
        $community_list = Community::all($cond);
        $c_s_r = new CommunitySellerRelation();
        $s_c_l = $c_s_r->where(["seller_id" => $seller->id])->column("community_id");
        foreach ($community_list as $k => $v) {
            if (in_array(
                $v->id,
                $s_c_l
            )) {
                $community_list[$k]->is_select = 1;
            } else {
                $community_list[$k]->is_select = 0;
            }
        }
        response_json(Code::NONE, $community_list);
    }


    /**
     *编辑商家-社区关系
     * 参数
     * community[]
     */
    public function seller_community_edit()
    {
        $this->check_login();
        $seller = Session::get_local_seller();
        if (empty($seller)) {
            response_json(Code::NO_SELLER);
        }
        $param = input();
        $relation_model = new CommunitySellerRelation();
        $relation_model->delSellerCommunityRelation($seller->id);
        if (isset($param['community'])) {
            $relation_model->addListSellerCommunityRelation($seller->id, $param['community']);
        }
        response_json(Code::NONE);
    }

    /**
     *确认接单
     * 参数 order_id
     */
    public function accept_order()
    {
        $param = input();
        if (!isset($param['order_id'])) {
            response_json(Code::PARAM_ERROR);
        }
        $order_id = $param['order_id'];
        /** @var  Order $order */
        $order = Order::get(["order_id" => $order_id]);
        if (empty($order)) {
            response_json(Code::ORDER_EMPTY);
        }
        if ($order->order_status_id >= OrderStatus::YIJIEDAI) {
            response_json(Code::ORDER_YIJIEDAN);
        }
        OrderStatus::yijiedan($order);
        response_json(Code::NONE);
    }

    /**
     *确认送达
     */
    public function querenshouhuo()
    {
        $param = input();
        if (!isset($param['order_id'])) {
            response_json(Code::PARAM_ERROR);
        }
        $order_id = $param['order_id'];
        /** @var  Order $order */
        $order = Order::get(["order_id" => $order_id]);
        if (empty($order)) {
            response_json(Code::ORDER_EMPTY);
        }
        if ($order->order_status_id >= OrderStatus::QUERENSHOUHUO) {
            response_json(Code::FAIL);
        }
        OrderStatus::rebates($order,
            sprintf("%s订单完成，系统执行返利", $order->order_id)
        );
        OrderStatus::querenshouhuo($order);
        response_json(Code::NONE);
    }


}